package com.basker.pisces.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

/**
 * 分页工具类
 *
 * @author hangwen
 */
public class PageUtils {

    /**
     * 获取分页后的每页数据
     *
     * @param pageSize
     * @param allDatas
     * @return
     */
    public static <T> List<T[]> getAllPageDatas(int pageSize, T[] allDatas) {
        if (ArrayUtils.isEmpty(allDatas)) {
            return Collections.emptyList();
        }

        int totalCount = allDatas.length;
        int totalPages = getTotalPageCount(totalCount, pageSize);
        List<T[]> pageDatas = new ArrayList<T[]>(totalPages);

        int from = 0, to = 0;

        for (int i = 0; i < totalPages; i++) {
            from = pageSize * i;
            to = pageSize * (i + 1);
            if (i == totalPages - 1) {
                to = totalCount;
            }

            T[] currentPageDatas = Arrays.copyOfRange(allDatas, from, to);
            pageDatas.add(currentPageDatas);
        }

        return pageDatas;
    }

    public static int getTotalPageCount(int totalCount, int pageSize) {
        if (totalCount == 0) {
            return 0;
        }

        if (pageSize > 0) {
            int pageCount = totalCount / pageSize;
            int mod = totalCount % pageSize;

            if (mod > 0) {
                return pageCount + 1;
            } else {
                return pageCount;
            }
        }

        return 0;
    }

}
